package com.itheima.reggie.contronller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryContronller {

    @Autowired
    private CategoryService categoryService;


    @PostMapping
    public R<String> saveCategory(@RequestBody Category category) {
        log.info(category.toString());

        categoryService.save(category);

        return R.success("新增分类成功");

    }


    @GetMapping("/page")
    public R<Page> pageCategory(Integer page, Integer pageSize) {
        Page<Category> pageCgy = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        categoryService.page(pageCgy, lambdaQueryWrapper);

        return R.success(pageCgy);
    }

    @DeleteMapping
    public R<String> delCg(Long id) {

        categoryService.removeById(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> updateCg(@RequestBody Category category) {

        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> listCategory(Integer type) {
        //根据type查表
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(type != null,Category::getType, type);
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }


}
